package model

import (
	"go-crud-demo/common"
	"log"
)

type Student struct {
	ID   int
	Name string
}

func GetAllStudents() (students []Student, err error) {
	sql := "SELECT * FROM characters"
	rows, err := common.Db.Query(sql)
	if err != nil {
		return
	}
	for rows.Next() {
		s := Student{}
		err = rows.Scan(&s.ID, &s.Name)
		if err != nil {
			return
		}
		students = append(students, s)
	}
	return
}

func (s *Student) EditStudent() (err error) {
	_, err = common.Db.Exec("UPDATE characters SET Name=? WHERE Id=?", s.Name, s.ID)
	return
}

func DeleteStudent(id string) (err error) {
	_, err = common.Db.Exec("DELETE FROM characters WHERE Id=?", id)
	return
}

func (s *Student) Insert() (err error) {
	sqlStr := `INSERT INTO characters (Name) VALUE (?);`
	stmt, err := common.Db.Prepare(sqlStr)
	if err != nil {
		log.Fatalln(err)
	}
	defer stmt.Close()
	_, err = stmt.Exec(s.Name)
	if err != nil {
		log.Fatalln(err)
	}
	// 查询插入数据的id
	err = common.Db.QueryRow("SELECT IFNULL(LAST_INSERT_ID(), -1);").Scan(&s.ID)
	if err != nil {
		log.Fatalln(err)
	}
	return
}
